using System.Collections.Generic;
using System.Net;
using MimeCloud.Foundations.Helpers;

namespace MimeCloud.Foundations.Extensions
{
    public static class WebClientExtensions
    {
        public static string PerformHttpPost(this WebClient client, string uri, IDictionary<string, string> postParams)
        {
            return PerformHttpPost(client, uri, postParams, true);
        }

        public static string PerformHttpPost(this WebClient client, string uri, IDictionary<string, string> postParams, bool encodeParams)
        {
            return PerformHttpPost(client, uri, postParams, encodeParams, "application/x-www-form-urlencoded");
        }

        public static string PerformHttpPost(this WebClient client, string uri, IDictionary<string, string> postParams, bool encodeParams, string contentType)
        {
            string queryString = WebHelper.ToQueryString(postParams, encodeParams);
            client.Headers.Add("Content-Type", contentType);
            string uploadResult = null;
            try
            {
                uploadResult = client.UploadString(uri, "POST", queryString);
            }
            catch (WebException ex)
            {
                /*
                 * Maybe throw a new exception with response
                 * as the message and ex as the innerexception
                 */
                string responseString = WebHelper.GetWebExceptionResponse(ex);
                throw;
            }
            return uploadResult;
        }
    
    }
}
